import { useEffect, useRef, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import NavBar from './navBar';
import SecondNavBar from './secondNavBar';

export interface MenuTypes {
  // 菜单名称
  label: string;
  // 一级菜单图标
  icon?: any;
  // 唯一识别码
  key: string;
  // 点击后要跳转的链接
  link?: string;
  // 二级菜单列表 一级菜单上需要 二级上不需要
  subs?: MenuTypes[];
  // 父级菜单的key 任何一级都不用配 会自动赋值
  parent?: string;
  // 路由数组，不是为了跳转，只为匹配上任何一个后有个选中状态
  links?: string[];
  path: string;
  // parentPath?: string;
  component?: string;
  isDetail?: boolean;
}

interface Props {
  menus: MenuTypes[];
}

export default function MainNavBar({ menus }: Props) {
  const location = useLocation();
  const navigate = useNavigate();
  const menuMapRef = useRef<{ [x: string]: MenuTypes }>({});
  const [currentMenuKey, setCurrentMenuKey] = useState<string | undefined>('');
  const [currentSubKey, setCurrentSubKey] = useState<string | undefined>('');
  // 点击过的历史记录
  const [historyList, setHistoryList] = useState<MenuTypes[]>([]);
  useEffect(() => {
    let map: { [x: string]: MenuTypes } = {};
    for (let m of menus) {
      map[m.key] = Object.assign({}, m, { parent: null });
      if (m.subs?.length) {
        for (let s of m.subs) {
          if (!s.path.endsWith('detail/:id')) {
            map[m.key + s.key] = Object.assign({}, s, { parent: m.key });
          }
        }
      }
    }
    menuMapRef.current = map;
  }, [menus]); //eslint-disable-line

  function setOldShortcuts(item: MenuTypes) {
    let old: MenuTypes[] = JSON.parse(localStorage.getItem('shortcuts') ?? '[]');
    for (let i = 0; i < old.length; i++) {
      if (old[i].key === item.key) {
        old.splice(i, 1);
        break;
      }
    }
    old.unshift(item);
    localStorage.setItem('shortcuts', JSON.stringify(old));
  }

  useEffect(() => {
    // 每次路由变化都重新确认要选中的一级菜单和二级菜单
    let pathname = location.pathname;
    let keys = Object.keys(menuMapRef.current);
    for (let k of keys) {
      // 查询所有菜单
      let menu = menuMapRef.current[k];
      if (menu) {
        // 如果路由地址和当前菜单的路由一致，直接选中当前的菜单
        if (pathname.toLowerCase() === (menu.link ?? '').toLowerCase() || pathname === `${menu.link}/`.toLowerCase()) {
          // 如果没有parent，说明当前是一级菜单，选中自己就好了
          if (!menu.parent) {
            setCurrentMenuKey(menu.key);
            setCurrentSubKey('');
          } else {
            // 有parent 说明当前是二级菜单，选中父级和自己
            setCurrentMenuKey(menu.parent);
            calcHistory(menu, true);
            setCurrentSubKey(menu.key);
            setOldShortcuts(menu);
          }
          break;
        } else if (menu.links) {
          // 如果不一致，则判断关联的菜单
          let has = false;
          for (let l of menu.links) {
            // 如果当前路由是以关联菜单开头或包含关联菜单，也选中当前菜单
            if (
              pathname.toLowerCase().startsWith(l.toLowerCase()) ||
              pathname.toLowerCase().includes(l.toLowerCase())
            ) {
              has = true;
              if (!menu.parent) {
                setCurrentMenuKey(menu.key);
                setCurrentSubKey('');
              } else {
                setCurrentMenuKey(menu.parent);
                calcHistory(menu, true);
                setCurrentSubKey(menu.key);
                setOldShortcuts(menu);
              }
              break;
            }
          }
          if (has) {
            break;
          }
        }
      }
    }
  }, [location, menus]); //eslint-disable-line

  function handleMenuChange(item?: MenuTypes) {
    if (!item) {
      setCurrentMenuKey('');
      setCurrentSubKey('');
      return;
    }
    if (item.link?.startsWith('http')) {
      window.open(item.link, '_blank');
      return;
    }
    setCurrentMenuKey(item.key);
    let subs = [];
    let keys = Object.keys(menuMapRef.current);
    for (let k of keys) {
      let menu = menuMapRef.current[k];
      if (menu.parent === item.key) {
        subs.push(menu);
      }
    }
    let link = item.link;
    if (subs.length) {
      calcHistory(subs[0], true);
      setCurrentSubKey(subs[0].key);
      setOldShortcuts(subs[0]);
      link = subs[0].link;
    } else {
      setOldShortcuts(item);
    }

    if (link) {
      navigate(link);
    }
  }

  function handleSubChange(item?: MenuTypes) {
    if (!item) {
      setCurrentMenuKey('');
      setCurrentSubKey('');
      return;
    }
    if (item.path.startsWith('http')) {
      window.open(item.path, '_blank');
    } else if (item.link) {
      calcHistory(item, true);
      setCurrentSubKey(item.key);
      setOldShortcuts(item);
      navigate(item.link);
    }
  }

  function calcHistory(item: MenuTypes, plus: boolean) {
    let list = [];
    let has = false;
    historyList.forEach((i) => {
      if (item.key === i.key) {
        if (plus) {
          has = true;
          list.push(i);
        }
      } else {
        list.push(i);
      }
    });
    if (plus && !has) {
      list.push(item);
    }
    if (list.length > 10) {
      list = list.slice(-10);
    }
    setHistoryList(list);
  }

  let subs: MenuTypes[] = [];
  if (currentMenuKey) {
    let keys = Object.keys(menuMapRef.current);
    for (let k of keys) {
      let menu = menuMapRef.current[k];
      if (menu.parent === currentMenuKey) {
        subs.push(menu);
      }
    }
  }

  return (
    <div className="main-nav-bar">
      <NavBar menu={menus} current={currentMenuKey} onChange={handleMenuChange} />
      <div className="flex-1 second-nav-bar-block">
        <SecondNavBar menu={subs} current={currentSubKey} onChange={handleSubChange} />
        {/* <div className="d-flex-r pt-10 pl-20 pb-10">
          {historyList.map((i) => (
            <div
              key={i.key}
              className={`d-flex-r ai-center mr-10 ${
                currentSubKey === i.key ? 'text-primary-color' : 'text-second-color'
              }`}
            >
              <span className="cursor-pointer omit-text mr-10" onClick={() => handleSubChange(i)}>
                {i.label}
              </span>
              <CloseOutlined className="cursor-pointer" onClick={() => calcHistory(i, false)} />
              <div className="history-line" />
            </div>
          ))}
        </div> */}
        <div className="flex-1 scroll-bar-h-min">
          <Outlet />
        </div>
      </div>
    </div>
  );
}
